<template>
  <div>
    <custom-table
      ref=" "
      :columns="columns"
      :query="queryParams"
      :row-btn="rowBtn"
      :head-btn="headBtn"
      :show-head-btn="['flush','delete']"
      v-bind="$attrs"
      v-on="listeners"
      :show-row-btn="['delete']"
      :HeadBtnColSize="6"
      @tap-head-btn="onTapHeadBtn"
      @tap-row-btn="onTapRowBtn"
      @row-dblclick="onRowDbClick"
    >
    <template v-slot:status>
      <!-- <div style="color:red; background-color: aqua;">{{row.address}}内容</div> -->
      <el-tag type="warning">预警</el-tag>
    </template>
    <template slot="search">
<el-col :span="18" :xs="24">
      <div class="searchFrame">
  <span class="demonstration">预警时间设置(天数):</span>
      <div style="width: 140px;">
        <el-input style="width:100%;" placeholder="请填写天数" type="Number" v-model="input"></el-input>
      </div>
    <button class="searchClass" @click="preserve">保存</button>
    <!-- <el-button :loading="downloadLoading" class="filter-item" type="text" size="mini" icon="el-icon-download" @click="handleDownload">导出</el-button> -->
    </div>

    </el-col>
    </template>
    </custom-table>

  </div>

</template>

<script>
import tableMixin from '@/utils/mixin/custom-table'
import { showLoading, hideLoading } from '@/utils'
import curd from '@/api/curd'
// import mock from '@/utils/mixin/mock'
// var Mock = require('mockjs')
// import { randomNum } from '@/utils'

export default {
  data() {
    return {
      input: '',
      total: {},
      value: '',
      downloadLoading: false,
      listdata: [], // 导出的数据
      columns: [
        { name: '房号', field: 'room.name', type: 'tag',
          format(col, row) {
            if (Object.prototype.hasOwnProperty.call(row, 'room')) {
              return row.room.building.name + row.room.building.building_number + row.room.name
            } else {
              return ''
            }
          }
        },
        { name: '租户', field: 'User.real_name', type: 'tag',
          format(col, row) {
            if (row.user_id == 0) {
              return null
            } else {
              return row.User.real_name
            }
          } },
        { name: '月用水量', field: 'm_water', after: '吨', type: 'tag' },
        { name: '水费', field: 'water_price', after: '元', type: 'tag' },
        { name: '月用电量', field: 'm_electricity', after: '度', type: 'tag' },
        { name: '电费', field: 'electricity_price', after: '元', type: 'tag' },
        { name: '日期', field: 'fee_date', type: 'tag'
        },
        { name: '金额', field: 'fee', after: '元', type: 'tag' },
        { name: '状态', field: 'status', type: 'tag', opts: {}, label: false },
        { name: '添加时间', field: 'create_time' }
      ],

      headBtn: [
      ]
    }
  },
  components: {},
  mixins: [
    tableMixin
    //  mock
  ],
  computed: {
    rowBtn() {
      return [
        {
          name: '催收',
          key: 'notice',
          confirm: '确认对{room_name}进行发送催收通知吗？'
          // input: [
          //   { name: '图片', field: 'image', width: 150, required: true }
          // ]
          // show(row) {
          // }
        }
      ]
    }

  },
  props: {},
  filters: {},
  created() {
    var that = this
    that.onLoad()
    setTimeout(() => {
      console.log('table_$attrs', this.$attrs)
      console.log('table_listeners', this.listeners)
    }, 2000)
  },
  methods: {
    // 修改预警天数
    preserve() {
      var that = this
      var data = {
        time: that.input
      }
      showLoading('设置中...')
      that.curd.get('saveWarningTime', data).then(res => {
        console.log('获取成功', res)
        hideLoading()
        that.onTapHeadBtnFlush({})
      }, hideLoading)
    },
    // 导出数据
    handleDownload() {
      var that = this
      // console.log('startTime', this.startTime)
      // console.log('lastTime', this.lastTime)
      // console.log('housing_id', this.value)
      var data = {}
      if (this.startTime && this.lastTime) {
        var startTime = Date.parse(new Date(that.startTime).toString()) / 1000 // 开始时间戳
        var lastTime = (Date.parse(new Date(that.lastTime).toString()) / 1000) + 86399 // 结束时间戳
        data['startTime'] = startTime
        data['lastTime'] = lastTime
      }
      if (this.startTime) {
        if (!this.lastTime) {
          this.$message({
            message: '请把结束时间也选上',
            type: 'warning'
          })
          return
        }
      }
      if (this.lastTime) {
        if (!this.startTime) {
          this.$message({
            message: '请把开始时间也选上',
            type: 'warning'
          })
          return
        }
      }
      if (this.value != 0) {
        data['housing_id'] = this.value
      }

      // console.log('data', data)
      this.downloadLoading = true
      showLoading('导出中...')
      curd('payRecord').get('getExportList', data).then(res => {
        console.log('获取成功', res.data)
        this.listdata = res.data
        this.down(res.data)
      })
    },
    down(rows) {
      const headers = {
        '房间号': 'room_name',
        '租户': 'real_name',
        '月用水量(吨)': 'm_water',
        '水费': 'water_price',
        '月用电量(度)': 'm_electricity',
        '电费': 'electricity_price',
        '日期': 'fee_date',
        '金额(元)': 'fee',
        '状态': 'status'
      }
      // const filename = '对账单明细'
      // 懒加载
      import('@/vendor/Export2Excel').then(async excel => {
        // excel是引入文件（也就是@/ventor/Export2Excel）的导出对象
        // 获取所有的数据
        // const { rows } = await curd('check_in').index()
        console.log('rows', rows)
        const data = this.formatJson(headers, rows) // 返回的data就是我们转化后的数据
        excel.export_json_to_excel({
          // 要求转出的表头是中文
          header: Object.keys(headers), // 表头 必填
          data, // //具体数据 必填
          filename: '缴费单信息', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
        this.$notify({
          title: '导出成功',
          // message: '这是一条成功的提示消息',
          type: 'success'
        })
        this.downloadLoading = false
        hideLoading()
        // console.log('excel', excel)
        // 拿到的数据是这种
        //  [{ username: 'xxx', mobile: 'xxx', ... }, { username: 'xxx', mobile: 'xxx', ... }]
        // 要转化的是如下这种
        // header: ['姓名', '手机号', '入职日期', ...]
        // data: [['张三', '138xxxxxxxx', '1992-08-04', ...], ['李四', '135xxxxxxxx', '1992-08-04', ...]]
      })
    },
    formatJson(headers, rows) {
      return rows.map(item => {
        console.log(item)
        return Object.keys(headers).map(k => {
          // if (headers[k] === 'timeOfEntry' || headers[k] === 'correctionTime') {
          //   return formatDate(item[headers[k]]) // 返回格式化之前的时间
          // } else if (headers[k] === 'formOfEmployment') {
          //   return EmployeeEnum.hireType[item.formOfEmployment] ? EmployeeEnum.hireType[item.formOfEmployment] : '未知'
          // }
          return item[headers[k]]
        })
      })
    },
    // 发送催收通知
    onTapRowBtnNotice(data) {
      console.log(data)
      var that = this
      showLoading('发送中...')
      that.curd.post('sendWorthMessage', data).then(res => {
        hideLoading()
        // console.log('发送成功', res)
        this.$notify({
          title: '发送成功',
          type: 'success'
          // message: ('发送成功')
        })
      }, hideLoading)
    },

    // 搜索事件
    search() {
      var that = this

      var startTime = Date.parse(new Date(that.startTime).toString()) / 1000 // 开始时间戳
      var lastTime = (Date.parse(new Date(that.lastTime).toString()) / 1000) + 86399 // 结束时间戳
      if (isNaN(startTime)) {
        alert('请选择开始日期')
        return false
      } else if (isNaN(lastTime)) {
        alert('请选择结束日期')
        return false
      }
      // console.log('我被点击了')
      // that.queryParams = {}
      that.$set(this.params, 'filter[fee_date]', startTime + ',' + lastTime)
      that.$set(this.params, 'op[fee_date]', 'BETWEEN')
      this.$emit('load', { query: this.queryParams })
      that.getTotal(this.queryParams)
    },

    // 初次加载
    onLoad() {
      var that = this
      that.curd.get('getWarningTime').then(res => {
        console.log('获取成功', res)
        that.input = res.data.time
      })
      // that.getTotal()
    },
    // 获取缴费总汇
    getTotal(queryParams = null) {
      var that = this
      that.curd.get('getTotal', queryParams).then(res => {
        console.log('获取缴费总汇', res)
        if (res.msg == '获取成功') {
          that.total = res.data
        }
      })
    },

    // 选择小区
    selectOk(e) {
      var that = this
      that.$set(this.params, 'room_id', e)
      console.log('我被选中了', this.queryParams)
      this.$emit('load', { query: this.queryParams })
      that.getTotal(this.queryParams)
    },
    // 取消双击编辑功能
    onRowDbClick() {}
    /*
    onLoad() {
      Mock.Random.extend({
        roomType(date) {
          return this.pick(['单间', '一房一厅', '两房一厅', '三房一厅', '豪华套房'])
        },
        area() {
          return randomNum(50, 200)
        },
        amount() {
          return randomNum(500, 2000)
        },
        buildingName(data) {
          return this.pick(['A栋', 'B栋', 'C栋', 'D栋']) + randomNum(1, 999).toString().padStart(3, '0')
        },
        status() {
          return this.pick(['待缴费', '已缴费'])
        },
        roomNo() {
          return '琼花湖' + randomNum(1, 10) + '栋' + randomNum(1, 999).toString().padStart(3, '0')
        }
      })
      var data = Mock.mock({
        // 属性 list 的值是一个数组，其中含有 1 到 10 个元素
        'list|20': [{
          // 属性 id 是一个自增数，起始值为 1，每次增 1
          'id|+1': 1,
          'number': '@roomno',
          'nickname': '@cname',
          'water|1-400': 1,
          'power|1-299': 1,
          'water_num|1-100': 1,
          'power_num|1-299': 1,
          'area': '@area',
          'amount': '@amount',
          'date': '@date',
          'create_time': '@now',
          'status': '@status',
          'room_type': '@roomtype',
          'name': '@buildingname'
        }]
      })

      console.log('mock', data)

      this.setMockData(data)
    }
    */
  }
}
</script>

<style lang="scss">

.demonstration{
    margin-left: 5px;
    color: #8492a6;
    font-size: 14px;
    // width: 20px;
  // padding:15px
  // margin-top: 5px;
  // color: #f4f4f5;
}
.searchClass{
  padding: 7px 15px;
  font-size: 12px;
  margin-left: 10px;
  border-radius: 3px;
  margin-right: 20px;
  width: 100px;
  // position: fixed;
  // top: 98px;
  // left: 90%;
  // z-index: 9;
  // display: flex;
  // align-items: center;
  // justify-content: center;
  color: #FFFFFF;
  background-color: #1890ff;
  // border-color: #1890ff;
}
.searchFrame{
  display: flex;
  width: 100%;
  align-items: center;
  justify-content:flex-end;
  // padding: 15px;
  // flex-direction: row-reverse;
  // height: 90px;
  // padding-right: 20px;
  // padding: 10px 20px;
}
.el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
  // .demonstrations {
  //   display: block;
  //   color: #8492a6;
  //   font-size: 14px;
  //   margin-bottom: 20px;
  // }
</style>
